package com.gserver.netty.coder;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gserver.netty.domain.Message;

public class ObjectEncoder extends OneToOneEncoder {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel,
			Object msg) throws Exception {
		log.debug("ObjectEncoder.encode()" + "threadId="
				+ Thread.currentThread().getId());
		Message message = (Message) msg;
		byte[] data = message.getData();
		int length = 0;
		if (data != null) {
			length = data.length + 4;
		} else {
			length = 4;
		}
		ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
		buf.writeInt(length);
		buf.writeShort(message.getHandler());
		buf.writeShort(message.getCmd());
		if (length > 4) {
			buf.writeBytes(data);
		}
		log.debug("ObjectEncoder.encode()" + " length:" + length + " handler:"
				+ message.getHandler() + " cmd:" + message.getCmd());
		return buf;
	}

}
